package bupt.xixi.entity;

import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class RequestHandler {

    private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);

    // 反射调用service服务处理rpcRequest
    public Object handle(RpcRequest rpcRequest, Object service) {
        Object result = invokeTargetMethod(rpcRequest, service);
        return result;
    }

    @SneakyThrows
    private Object invokeTargetMethod(RpcRequest rpcRequest, Object service) {
        Method method;
        try {
            method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            return method.invoke(service, rpcRequest.getParameters());
        } catch (NoSuchMethodException e) {
            logger.error("调用远程方法时发生异常：{}", e.getMessage());
        }
        return null;
    }

}
